import { readRawBody, getQuery, getMethod } from 'h3'

export default defineEventHandler(async (event) => {
  const $config = useRuntimeConfig()
  const method = getMethod(event).toUpperCase()
  const CLIENT_ID = $config.public.tiwtter_appid
  const CLIENT_SECRET = $config.public.tiwtter_appsecret
  const credentials = `${CLIENT_ID}:${CLIENT_SECRET}`
  const base64Credentials = Buffer.from(credentials).toString('base64')

  let body, from
  let bodyData = {}
  if (method !== 'GET') {
    body = await readRawBody(event)
    bodyData = JSON.parse(body)
    const paramsStr = Buffer.from(bodyData.state, 'base64').toString()
    const { challenge, redirect_uri, from: _from } = JSON.parse(paramsStr)
    from = _from
    bodyData.code_verifier = challenge
    bodyData.redirect_uri = redirect_uri
    bodyData.grant_type = 'authorization_code'
    bodyData.client_id = CLIENT_ID
    delete bodyData.state
  }

  try {
    const res = await $fetch('/oauth2/token', {
      method,
      baseURL: 'https://api.twitter.com/2',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${base64Credentials}`
      },
      params: bodyData
    })
    if (!res || res.access_token === undefined) throw new Error('login failed')
    const { access_token } = res
    console.log(res, 'login success')
    const resoponse = await $fetch('/users/me', {
      method: 'GET',
      baseURL: 'https://api.twitter.com/2',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${access_token}`
      },
      params: {
        'user.fields': 'id,name,username,profile_image_url,pinned_tweet_id,public_metrics,location,url,description,created_at',
        'expansions': 'pinned_tweet_id'
      }
    })
    if (!resoponse || resoponse.data === undefined) throw new Error('get user info failed')
    console.log(resoponse, 'get user info success')
    return { from, ...res, userInfo: resoponse.data } || {}
  } catch (error) {
    console.error(error)
    return { error: 'login failed' }
  }
})
